package com.appkubes.mall.restful.application.user.user.service.impl;

import com.appkubes.common.exception.BusinessException;
import com.appkubes.common.utils.data.date.DateUtils;
import com.appkubes.mall.core.entity.MallPromoter;
import com.appkubes.mall.core.entity.MallUser;
import com.appkubes.mall.core.entity.MallUserHierarchy;
import com.appkubes.mall.core.service.BaseMallUserService;
import com.appkubes.mall.core.service.impl.BaseMallPromoterServiceImpl;
import com.appkubes.mall.core.service.impl.BaseMallUserServiceImpl;
import com.appkubes.mall.core.service.impl.BaseMallUtmSourceServiceImpl;
import com.appkubes.mall.restful.application.promoter.annotation.UserRegisterEvent;
import com.appkubes.mall.restful.application.promoter.entity.eo.UserRegisterEO;
import com.appkubes.mall.restful.application.user.account.account.entity.dto.OrderPayUserAccountDTO;
import com.appkubes.mall.restful.application.user.account.account.service.UserAccountService;
import com.appkubes.mall.restful.application.user.hierarchy.service.UserHierarchyService;
import com.appkubes.mall.restful.application.user.user.entity.vo.HierarchyVO;
import com.appkubes.mall.restful.application.user.user.entity.vo.UserActiveVO;
import com.appkubes.mall.restful.application.user.user.entity.vo.UserRegisterVO;
import com.appkubes.mall.restful.application.user.user.service.UserService;
import com.appkubes.mall.restful.application.utm.service.UtmService;
import com.appkubes.mall.restful.event.event.EventService;
import com.appkubes.mall.restful.fintech.user.baseInfo.entity.vo.UserBaseInfoVO;
import com.appkubes.mall.restful.fintech.user.baseInfo.service.UserBaseInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Rongjie
 * @Date: 2020/2/27
 * @Description:
 */
@Service
@Slf4j
public class UserServiceImpl extends BaseMallUserServiceImpl implements UserService {
    @Resource
    UtmService utmService; //渠道跟踪

    @Resource
    UserHierarchyService userHierarchyService; //用户层级服务
    @Resource
    UserAccountService accountService; //用户账户服务

    @Resource
    BaseMallUserService mallUserService;


    @Value("${kylin.plugin.hierarchy.decreaseRate}")
    private double decreaseRate;

    @Resource
    BaseMallPromoterServiceImpl mallPromoterService;

    @Resource
    UserBaseInfoService userBaseInfoService;

    @Override
    public Boolean isActive(UserActiveVO userActiveVO) {
        MallUser entity = new MallUser();
        entity.setUserKey(userActiveVO.getUserKey());
        entity.setRegisterType(userActiveVO.getToken());
        Integer count = mallUserService.selectCount(entity);
        return count > 0;
    }

    /**
     * 用户注册
     *
     * @param registerVO
     * @return
     */
    @Override
    @Transactional(rollbackFor = BusinessException.class)
    public MallUser register(UserRegisterVO registerVO) throws BusinessException {
        //注册用户
        MallUser queryUser = new MallUser();
        queryUser.setTel(registerVO.getTel());
        Integer count = this.selectCount(queryUser);
        if (count > 0) {
            throw new BusinessException("用户手机号已经注册");
        }
        MallUser user = new MallUser();
        BeanUtils.copyProperties(registerVO, user);

        Integer now = DateUtils.getCurrentTimestamp();
        user.setCreateTime(now);
        user.setUpdateTime(now);
        Boolean flag = this.save(user);
        if (!flag) {
            throw new BusinessException("用户基础信息注册失败");
        }

        //统计渠道
        utmService.register(user.getUserKey(), registerVO);

        //统计用户等级
        userHierarchyService.register(user.getUserKey(), registerVO);

        //添加fintech用户
        addFintechUserInfo(user, registerVO);
        return user;
    }


    /**
     * 添加fintech用户信息
     * @param user
     * @param registerVO
     */
    @Override
    public void addFintechUserInfo(MallUser user, UserRegisterVO registerVO) {
        UserBaseInfoVO userBaseInfoVO = new UserBaseInfoVO();
        userBaseInfoVO.setUserKey(user.getUserKey());
        userBaseInfoVO.setPhone(user.getTel());
        userBaseInfoVO.setUserDevice(registerVO.getPlatformType());

        // 推广员
        if (registerVO.getPromoterKey() != null && !"".equalsIgnoreCase(registerVO.getPromoterKey())) {
            String promoterKey = registerVO.getPromoterKey();
            MallPromoter mallPromoter = mallPromoterService.getById(promoterKey);
            userBaseInfoVO.setRefChannelId(promoterKey);
            userBaseInfoVO.setRefChannelName(mallPromoter.getPromoterName());
        }
        // 渠道
        if (registerVO.getUtmSource() != null && !"".equalsIgnoreCase(registerVO.getUtmSource())) {
            String utmSourceKey = registerVO.getUtmSource();
            userBaseInfoVO.setUserSource(utmSourceKey);
        }
        // 经纪人
        if (registerVO.getInvitorKey() != null && !"".equalsIgnoreCase(registerVO.getInvitorKey())) {
            String invitorKey = registerVO.getInvitorKey();

            // 获取父推广员的推广信息
            MallUserHierarchy mallUserHierarchy = userHierarchyService.getById(invitorKey);
            MallUser invitorUser = getById(invitorKey);
            if (mallUserHierarchy == null || invitorUser == null) {
                throw new BusinessException("链接已失效");
            }
            userBaseInfoVO.setRefUserId(invitorKey);
            userBaseInfoVO.setRefUserName(invitorUser.getName());
            userBaseInfoVO.setRefUserPhone(invitorUser.getTel());
            // 补偿
            if (mallUserHierarchy != null && !StringUtils.isEmpty(mallUserHierarchy.getPromoterKey())) {
                userBaseInfoVO.setRefChannelId(mallUserHierarchy.getPromoterKey());
                MallPromoter mallPromoter = mallPromoterService.getById(mallUserHierarchy.getPromoterKey());
                if (mallPromoter != null) {
                    userBaseInfoVO.setRefChannelName(mallPromoter.getPromoterName());
                }
            }

        }
        userBaseInfoService.register(userBaseInfoVO);
    }

    @Override
    public Boolean onOrderPay(String userKey, OrderPayUserAccountDTO orderPayUserAccountDTO) {
        log.info("user:" + userKey);
        MallUserHierarchy mallUserHierarchy = userHierarchyService.getById(userKey); //获取用户的层级信息
        if (mallUserHierarchy == null) {
            //没有层级关系，不发放佣金
            return true;
        }

        // 参与分佣的经纪人列表
        List<HierarchyVO> parentKeyList = getHierarchyList(mallUserHierarchy);

        parentKeyList.forEach(hierarchyVO -> {
            OrderPayUserAccountDTO innerOrderPayUserAccountDTO = new OrderPayUserAccountDTO();
            BeanUtils.copyProperties(orderPayUserAccountDTO, innerOrderPayUserAccountDTO);
            innerOrderPayUserAccountDTO.setUserKey(hierarchyVO.getParentKey());
            innerOrderPayUserAccountDTO.setBrokerage(innerOrderPayUserAccountDTO.getBrokerage()
                    .multiply(BigDecimal.valueOf(hierarchyVO.getRate())));
            accountService.onOrderPay(innerOrderPayUserAccountDTO);
        });
        return null;
    }

    private List<HierarchyVO> getHierarchyList(MallUserHierarchy mallUserHierarchy) {
        List<HierarchyVO> parentKeyList = new ArrayList<>();
        if (mallUserHierarchy.getParentUserKey() != null) {
            HierarchyVO hierarchyVO = new HierarchyVO();
            hierarchyVO.setParentKey(mallUserHierarchy.getParentUserKey());
            hierarchyVO.setRate(1.0);
            parentKeyList.add(hierarchyVO);
        }
        if (mallUserHierarchy.getParentUserKey2() != null) {
            HierarchyVO hierarchyVO = new HierarchyVO();
            hierarchyVO.setParentKey(mallUserHierarchy.getParentUserKey2());
            hierarchyVO.setRate(1.0 * decreaseRate);
            parentKeyList.add(hierarchyVO);
        }
        if (mallUserHierarchy.getParentUserKey3() != null) {
            HierarchyVO hierarchyVO = new HierarchyVO();
            hierarchyVO.setParentKey(mallUserHierarchy.getParentUserKey3());
            hierarchyVO.setRate(1.0 * decreaseRate * decreaseRate);
            parentKeyList.add(hierarchyVO);
        }
        if (mallUserHierarchy.getParentUserKey4() != null) {
            HierarchyVO hierarchyVO = new HierarchyVO();
            hierarchyVO.setParentKey(mallUserHierarchy.getParentUserKey4());
            hierarchyVO.setRate(1.0 * decreaseRate * decreaseRate * decreaseRate);
            parentKeyList.add(hierarchyVO);
        }
        if (mallUserHierarchy.getParentUserKey5() != null) {
            HierarchyVO hierarchyVO = new HierarchyVO();
            hierarchyVO.setParentKey(mallUserHierarchy.getParentUserKey5());
            hierarchyVO.setRate(1.0 * decreaseRate * decreaseRate * decreaseRate * decreaseRate);
            parentKeyList.add(hierarchyVO);
        }
        return parentKeyList;
    }
}
